package com.tanhua.sso.controller;

import com.tanhua.common.pojo.User;
import com.tanhua.sso.service.UserService;
import com.tanhua.sso.vo.ErrorResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: my-tanhua
 * @description: 用户登录
 * @author: xuejingjing
 * @create: 2021-09-19 07:22
 **/
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;
    //前端发过来的是phone和code???是的。

    /**
     * 用户登录
     * @param param
     * @return
     */
    @PostMapping("loginVerification")
    public ResponseEntity<Object> login(@RequestBody Map<String,String> param){
        try {
            String phone = param.get("phone");
            String code = param.get("verificationCode");

            //返回的token
            String data = userService.login(phone,code);

            if(StringUtils.isNotBlank(data)){
                //如果不为空，则说明登录成功了
                Map<String, Object> result = new HashMap<String, Object>();
                String[] split = StringUtils.split(data, "|");
                 result.put("token",split[0]);
                 result.put("isNew",Boolean.valueOf(split[1]));
                 return ResponseEntity.ok(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        ErrorResult errorResult = ErrorResult.builder().errorCode("000002").errorMessage("denglushibai").build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);

    }

    /**
     * 校验token，根据token查询数据
     */
    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token") String token){
        return userService.queryUserByToken(token);
    }

}